package cn.desk.user.interceptor;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.desk.user.action.UserAction;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class SessionInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = LoggerFactory
			.getLogger(SessionInterceptor.class);

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpSession session = ServletActionContext.getRequest().getSession();

		Object user = session.getAttribute(UserAction.SESSION_KEY_USER);
		ActionSupport action = (ActionSupport) invocation.getAction();
		if (user == null) {
			LOGGER.debug("SESSION_KEY_USER is null");
			action.addActionError("EMUM0005");
			Map<String, ResultConfig> config = invocation.getProxy()
					.getConfig().getResults();
			ResultConfig input = config.get("input");
			if (input.getClassName().equals(JSONResult.class.getName())) {
				return "input";
			}
			return "login";
		}
		return invocation.invoke();
	}

}
